define(function(require, exports, module) {
    "use strict";
    var $ = require("$"),
        app = require("dist/application/app"),
        config = app.config,
        method = app.method;

    require("jquery_ui")
    var config_panel = require("./config")
    var _tmp_list_item = require("./template/list-item.html");
    var _tmp_list_page = require("./template/list-page.html");
    var Design = function() {
        this.widget = $(".js_widget");
        this.phone_container = $("#js_phone_container");
        this.config_container = $("#js_config_container");
        this.config_load = $(".js_load");
        this.dropped = false;
        this.config = window.design_config;
        this.action = this.actionHandler();
        this.init();
    }
    Design.prototype.init = function(el) {
        this.dragHandler();
        var _self = this;
        $(document).on("click", '.js_del_item', function(e) {
            e && e.stopPropagation();
            var $itme = $(this).closest('.list-item');
            $itme.fadeOut(function() {
                $itme.remove()
            });
            var data = {
                wid: $itme.attr("wid")
            };
            method.postd(_self.config.widget_del, function(d) {
                !config.issucceed(d) && config.msg.error(d.message || config.lang.removeError, d.url);
            }, data)
        });
        $(document).on('click', '.list-item', function(e) {
            _self.showConfig($(this).attr("wid"));
        })
    };

    Design.prototype.actionHandler = function() {
        var _self = this;
        return {
            add_widget: function(el) {
                var data = {
                    name: el.data("name")
                }
                method.postd(_self.config.widget_add, function(d) {
                    if (config.issucceed(d)) {
                        _self.getWidgetHtml(el, d.wid, data.name);
                        // _self.updateWidget();
                    } else {
                        config.msg.error(d.message || config.lang.widgetError, d.url)
                    }
                }, data)
            }
        }
    },
    Design.prototype.getWidgetHtml = function(el, wid, name) {
        var html = $(_tmp_list_item.format(this.config.widget_get.format(wid, name), wid));
        el.append(html.html());
        el.attr("wid", wid).removeData("name");
        this.showConfig(wid);

    },
    Design.prototype.showConfig = function(wid) {
        var _self = this;
        $(".js_tips").hide();
        wid && (function() {
            var formsConfig = $('.config_panel form');
            var formConfig = $('.config_panel form[wid="' + wid + '"]');
            _self.config_load.removeClass('hd');
            if (formConfig.length > 0) {
                formConfig.show();
                formConfig.siblings("form").hide();
                _self.config_load.addClass('hd');
            } else {
                $.ajax(_self.config.config_get.format(wid), {
                    type: "get",
                    dataType: "html"
                }).done(function(result) {
                    var $result = $(result);
                    _self.config_container.append($result);
                    $result.length > 0 && require.async("dist/form/init", function(form) {
                        $("button[type='submit']", $result).removeAttr('disabled');
                        form.init($result);
                        config_panel.init($result);
                    });
                }).fail(function() {
                    config.msg.info(config.lang.templateConfigLoadError)
                }).always(function() {
                    _self.config_load.addClass('hd');
                })
                formsConfig.hide();
            }


        })()
    };
    Design.prototype.getPageHtml = function(d) {
        var _self = this;
        d && $.each(d, function(index, item) {
            _self.phone_container.append(_tmp_list_item.format(_self.config.widget_get.format(item.id, item.name), item.id))
        });

    },
    Design.prototype.updateWidget = function() {
        var items = $(".list-item", this.phone_container);
        var data = $.map(items, function(item, index) {
            return $(item).attr("wid");
        });
        data && method.postd(window.design_config.widget_update, function() {
            //不处理成功 
        }, {
            data: window.JSON.stringify(data)
        })
    },
    Design.prototype.dragHandler = function() {
        var _self = this;
        this.widget.draggable({
            connectToSortable: _self.phone_container,
            revert: "invalid",
            helper: "clone",
            cursor: "move",
            scroll: false
        });
        this.phone_container.droppable({
            accept: ".widget",
            greedy: !0,
            drop: function(e, a) {
                _self.dropped = false;
                _self.dropOpt($(a.draggable))
            }
        }).sortable({
            revert: true,
            placeholder: "place_holder",
            axis: "y",
            opacity: 0.5,
            appendTo: _self.phone_container,
            connectWith: "#js_widget_list",
            cancel: ":input,button,.list-item-del",
            start: function() {
                _self.dropped = true;
            },
            stop: function() {
                _self.updateWidget()
            },
        });
    };
    Design.prototype.dropOpt = function(e) {
        var name = e.data();
        e.removeAttr('class').addClass('list-item').empty()
        this.action.add_widget(e);
    };


    window.design_config && (function() {
        var ds = new Design();
        if (window.design_config.data) {
            ds.getPageHtml(window.design_config.data)
        };
        window.setWidget = function(widget) {
            var item = $('.list-item[wid="' + widget.wid + '"]');
            $("iframe,.list-item-body,.list-item-cover", item).height(widget.height);
        }
        window.updateWidget = function(wid) {
            var $iframe = $('.list-item[wid="' + wid + '"] iframe');
            $iframe.attr("src", $iframe.attr("src"))
        }

    })()

})
